package leetcode.backtrace;

import java.util.*;

/**
 * @Description
 * @Author 26233
 * @Create 2021-03-30 23:59:37
 */
/*
给定一个 没有重复 数字的序列，返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
通过次数286,965提交次数368,848

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class LeetCode46_Permute {
    public List<List<Integer>> permute(int[] nums) {

        List<List<Integer>> result = new ArrayList<>();
        List<Integer> tempResult = new ArrayList<>();
        Set<Integer> alredyNavi = new HashSet<>();

        for (int i = 0; i < nums.length; i++) {
            permute(result, tempResult, alredyNavi, nums, i);
            tempResult.clear();
            alredyNavi.clear();
        }

        return result;
    }

    public void permute(List<List<Integer>> result, List<Integer> tempResult, Set<Integer> alredyNavi, int[] nums, int index){

        tempResult.add(nums[index]);
        alredyNavi.add(index);
        if (tempResult.size() == nums.length){
            List<Integer> r = new ArrayList<>(tempResult);
            result.add(r);
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!alredyNavi.contains(i)){
                permute(result, tempResult, alredyNavi, nums, i);
                alredyNavi.remove(i);
                tempResult.remove(new Integer(nums[i]));
            }
        }

    }

    //////////////不使用临时数组，在原数组找那个操作//////////////////
    public List<List<Integer>> permute2(int[] nums) {

        List<List<Integer>> result = new ArrayList<>();
        List<Integer> tempResult = new ArrayList<>();

        permute(result, tempResult, nums, 0);

        return result;
    }
    public void permute(List<List<Integer>> result, List<Integer> tempResult, int[] nums, int index){

        if(index == nums.length){
            List<Integer> r = new ArrayList<>(tempResult);
            result.add(r);
            return;
        }

        for (int i = index; i < nums.length; i++) {
            tempResult.add(nums[i]);

            int temp = nums[i];
            nums[i] = nums[index];
            nums[index] = temp;

            permute(result, tempResult, nums, index + 1);
            tempResult.remove(new Integer(nums[index]));

            temp = nums[i];
            nums[i] = nums[index];
            nums[index] = temp;


        }

    }

    public static void main(String[] args) {
        int[] input = new int[]{1, 2, 3};
        // List<List<Integer>> result = new LeetCode46_Permute().permute(input);
        List<List<Integer>> result = new LeetCode46_Permute().permute2(input);

        System.out.println("result = " + result);
    }
}
